const { SuccessModel, ErrorModel } = require('../model/resModel');
const { getCookieExpires } = require('../utils/helper');

const {
  getList,
  getDetail,
  login,
} = require('../controler/user')


// 统一的登录验证函数
const loginCheck = (req) => {
  console.log('req.session.username', req.session.username);
  if (!req.session.username) {
    return false;
  }
  return true;
}

const handleUserRouter = (req, res) => {
  const method = req.method // GET POST

  // 获取用户列表
  if (method === 'GET' && req.path === '/api/user/list') {
    const loginCheckResult = loginCheck(req);
    if (!loginCheckResult) {
      // 未登录
      res.end(
        JSON.stringify(new ErrorModel('尚未登录'))
      )
      return true;
    }

    getList().then(listData => {
      if (req.needSetCookie) {
        const userId = req.cookie.userid;
        res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
      }

      res.end(
        JSON.stringify(new SuccessModel(listData))
      )
    });
    return true;
  }

  // 获取用户详情
  if (method === 'GET' && req.path === '/api/user/detail') {
    const loginCheckResult = loginCheck(req);
    if (!loginCheckResult) {
      // 未登录
      res.end(
        JSON.stringify(new ErrorModel('尚未登录'))
      )
      return true;
    }

    const id = req.query.id
    getDetail(id).then(data => {
      if (req.needSetCookie) {
        const userId = req.cookie.userid;
        res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${getCookieExpires()}`)
      }

      res.end(
        JSON.stringify(new SuccessModel(data))
      )
    });
    return true;
  }

  // 登录
  if (method === 'POST' && req.path === '/api/user/login') {
    const { username, password } = req.body;
    const result = login(username, password)
    return result.then(data => {
      if (data.username) {
        // 设置 session
        req.session.username = data.username
        req.session.realname = data.realname

        return new SuccessModel()
      }
      return new ErrorModel('登录失败')
    })
  }

  return false;
}

module.exports = handleUserRouter;